package 力扣;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yyq
 * @create 2022-04-27 16:08
 */
public class leetcode40 {
    public static void main(String[] args) {
        leetcode40 leetcode40=new leetcode40();
        leetcode40.combinationSum2(new int[]{2,5,2,1,2},5);
    }
    int sum = 0;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> lists=new ArrayList<>();
        List<Integer> list=new ArrayList<>();
        int startIndex=0;
        Arrays.sort(candidates);
        backTracking(lists,list,candidates,target,startIndex);
        return lists;
    }

    private void backTracking(List<List<Integer>> lists, List<Integer> list, int[] candidates, int target,int startIndex) {
        if(sum>target)return;
        if(sum == target){


            lists.add(new ArrayList<>(list));
            return;
        }

        for (int i = startIndex; i < candidates.length; i++) {
            if(i>0&&candidates[i-1] == candidates[i]&&i!=startIndex){
                continue;
            }
            list.add(candidates[i]);
            sum = sum + candidates[i];
            backTracking(lists,list,candidates,target,i+1);
            list.remove(list.size()-1);
            sum = sum - candidates[i];
        }
    }
}
